package com.millstein.realtime.sink;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.millstein.realtime.bean.TableProcess;
import com.millstein.realtime.util.DruidDSUtil;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.List;

/**
 * @Description
 * @Author tsing
 * @Date 2024-09-27 11:01
 */
public class PhoenixSink extends RichSinkFunction<Tuple2<JSONObject, TableProcess>> {

    DruidDataSource druidDataSource;

    @Override
    public void open(Configuration parameters) throws Exception {
        druidDataSource = DruidDSUtil.getPhoenixConnection();
    }

    @Override
    public void close() throws Exception {
        druidDataSource.close();
    }

    @Override
    public void invoke(Tuple2<JSONObject, TableProcess> value, Context context) throws Exception {
        Connection connection = druidDataSource.getConnection();

        JSONObject data = value.f0.getJSONObject("data");
        TableProcess config = value.f1;

        StringBuilder sql = new StringBuilder();
        sql.append("upsert into ")
                .append(config.getSinkTable())
                .append(" (")
                .append(config.getSinkColumns())
                .append(") values (")
                .append(config.getSinkColumns().replaceAll("[^,]+", "?"))
                .append(")");
        System.out.println(sql.toString());

        PreparedStatement preparedStatement = connection.prepareStatement(sql.toString());
        List<String> columns = Arrays.asList(config.getSinkColumns().split(","));
        for (int i = 0 ; i < columns.size() ; i++) {
            String columnName = columns.get(i);
            Object columnValue = data.get(columnName);
            preparedStatement.setString(i + 1, columnValue == null ? null : columnValue + "");
        }

        preparedStatement.execute();
        connection.commit();

        preparedStatement.close();
        connection.close();
    }
}
